package com.dcbeida.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;


import java.io.IOException;
import java.util.Vector;

import com.dcbeida.R;
import com.dcbeida.bean.ResultModel;
import com.dcbeida.activity.inventory.InventoryActivity;
import com.dcbeida.listern.OnKeyListener;
import com.dcbeida.utils.GetApi;
import com.dcbeida.utils.Utils;
import com.dcbeida.zxing.camera.CameraManager;
import com.dcbeida.zxing.decoding.CaptureActivityHandler;
import com.dcbeida.zxing.decoding.InactivityTimer;
import com.dcbeida.zxing.view.ViewfinderView;


/**
 * 条码、二维码 扫描
 */
public class CaptureActivity extends QrExActivity {

    private String code = "";

    public static final int TYPE_CX = 0x1;

    public static final int TYPE_PD = 0x2;

    public static final int TYPE_RE = 0x3;

    public static final int TYPE_PAT = 0x4;//病人信息的结果

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;

    private boolean playBeep;

    private MediaPlayer mediaPlayer;
    private boolean vibrate;

    private RelativeLayout rel_title1;
    private LinearLayout rel_title2;
    private RelativeLayout rel_title3;

    private EditText et_tm;

    private int type = TYPE_CX;
    private String title;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture_pay);
        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        if (b != null) {
            if (b.containsKey("type")) {
                type = b.getInt("type");
            }

            if (b.containsKey("title")) {
                title = b.getString("title");
            }
        }

        setupview();


        // 初始化 CameraManager
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        if (type == TYPE_PAT) {
            viewfinderView.setTip("请扫码患者信息");
        }
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);

    }

    private void setupview() {
        rel_title1 = (RelativeLayout) findViewById(R.id.rel_title1);
        rel_title2 = (LinearLayout) findViewById(R.id.rel_title2);
        rel_title3 = (RelativeLayout) findViewById(R.id.rel_title3);

        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.img_back3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        et_tm = (EditText) findViewById(R.id.et_tm);

        if (type == TYPE_PD ) {
            rel_title1.setVisibility(View.GONE);
            rel_title2.setVisibility(View.GONE);
            rel_title3.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(title))
                ((TextView) findViewById(R.id.tv_name3)).setText(title);
        }else if(type == TYPE_RE){
            if (!TextUtils.isEmpty(title))
                ((TextView) findViewById(R.id.tv_pName)).setText(title);
        }else if(type == TYPE_PAT){
            if (!TextUtils.isEmpty(title))
                ((TextView) findViewById(R.id.tv_pName)).setText(title);
            et_tm.setHint("请输入患者信息");
        }
        findViewById(R.id.tv_sdsr).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rel_title1.setVisibility(View.GONE);
                rel_title2.setVisibility(View.VISIBLE);
            }
        });

        findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rel_title2.setVisibility(View.GONE);
                rel_title1.setVisibility(View.VISIBLE);
            }
        });

        TextView tv_confim = (TextView) findViewById(R.id.tv_confim);
        if (type == TYPE_PAT) {
            tv_confim.setVisibility(View.GONE);
            ((TextView) findViewById(R.id.tv_name3)).setText("扫码患者信息");

        }



        Utils.setOnKeySearch(et_tm, new OnKeyListener() {
            @Override
            public void search() {
                if (TextUtils.isEmpty(et_tm.getText()) || et_tm.getText().toString().trim().length() == 0
                ) {
                    if(type==TYPE_PAT){
                        Toast.makeText(CaptureActivity.this, "请输入病人号...", Toast.LENGTH_LONG).show();
                    }else {
                        Toast.makeText(CaptureActivity.this, "请输入条形码号...", Toast.LENGTH_LONG).show();
                    }
                    return;
                }

                code = et_tm.getText().toString().trim();
                //new getPayTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, code);
                startActivity_result();
            }
        });


    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;


    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
//		viewfinderView.drawResultBitmap(barcode);
        playBeepSoundAndVibrate();
        if (result == null)
            Toast.makeText(CaptureActivity.this, "扫描失败!", Toast.LENGTH_SHORT)
                    .show();
        code = result.getText();
        if (code.equals("")) {
            Toast.makeText(CaptureActivity.this, "扫描失败!", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Log.e("info", code);
            startActivity_result();
        }
    }

    private void startActivity_result() {
        Intent intent = new Intent();
        intent.putExtra("code", code);
        if (type == TYPE_PD) {
            intent.setClass(CaptureActivity.this, InventoryActivity.class);
            startActivity(intent);
        } else if (type == TYPE_CX) {
            intent.setClass(CaptureActivity.this, ResultActivity.class);
            startActivity(intent);
        } else {
            setResult(RESULT_OK, intent);
        }
        finish();

    }

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }

    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    private ProgressDialog mProgressDialog;

    class getPayTask extends AsyncTask<String, Void, ResultModel> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mProgressDialog == null) {
                mProgressDialog = ProgressDialog.show(CaptureActivity.this, "请稍候", "正在访问服务器数据...", true, true, null);
                mProgressDialog.setCancelable(false);

            }
        }

        @Override
        protected ResultModel doInBackground(String... params) {

            ResultModel ret = null;
            ret = GetApi.getdruginfo(params[0]);
            return ret;
        }

        @Override
        protected void onPostExecute(ResultModel ret) {
            super.onPostExecute(ret);
            if (mProgressDialog != null && mProgressDialog.isShowing())
                mProgressDialog.dismiss();
            if (ret.getErrcode() != 999) {
                Intent intent = new Intent();
                intent.setClass(CaptureActivity.this, ResultActivity.class);
                intent.putExtra("msg", ret.getErrmsg());
                intent.putExtra("code", code);
                startActivity(intent);

            } else {
                Toast.makeText(CaptureActivity.this, "获取数据失败,请查询网络是否正常", Toast.LENGTH_LONG).show();
            }
        }
    }


    private static final float BEEP_VOLUME = 0.10f;

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }


}
